<?php
namespace Home\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Admin\Controller\SmsApiController;

class IndexController extends BaseController {

    static $companyStatusMapping = array(
        "工商局" => "industry",
        "婚姻登记处" => "marriage",
        "不动产登记局" => "house",
        "人社局社保股" => "shebao",
        "人社局企业保险股" => "enterprise",
        "人社局机关事业保险股" => "goverment",
        "党委口和社区" => "community",
        "城市救助局" => "city",
        "车辆管理所" => "car",
        "公积金管理部" => "fund",
        "房产局开发股" => "estate",
    );

    public function index(){

        //政务内容分类
        $category = M("affairscategory")->order("seq asc")->select();
        $this->assign("category", $category);

        //焦点图片内容
        $where = array('active'=>'有效');
        $focus = M("affairsfocus")->where($where)->limit(4)->select();
        $this->assign('focus', $focus);

        //相关链接
        $links = M("links")->order("seq asc")->select();
        $this->assign("links", $links);

        //获取各分类相关信息
        $affairs = $this->fn_GetAffairsCategory();
        for($i=0; $i<count($affairs); $i++){
            $affairs[$i]["list"] = $this->fn_GetAffairsByCategory($affairs[$i]["id"], 7);
        }
        $this->assign("affairs", $affairs);

        $this->display();
    }

    public function query(){
        $this->assign("t", I("get.t"));
        $title = "申请进度查询";
        if(I("get.t")=="ns"){
            $title = "年审进度查询";
        }
        $this->assign("title", $title);
        $this->display();
    }

    public function msg(){

        $page = I("get.page")==null?1:intval(I("get.page"));
        $where = "reply is not null";
        $num = 5;
        $offset = ($page-1)*$num;
        $limit = $offset . "," . $num;

        $list = M("message")->where($where)->order("id desc")->limit($limit)->select();
        $this->assign("list", $list);

        $pages = $this->fn_GeneratePages($page, $where, $num);
        $this->assign("pages", $pages);

        //category相关
        $category = $this->fn_GetCategoryDict();
        $this->assign("category", $category);

        $this->display();
    }

    /**
     * 获取各小区的剩余房源数
     */
    private function fn_GetCommunityInfo(){
        $where = array("h.state"=>'闲置中', "h.type"=>'保障性住房');
        $data = M("house h")
            ->join(C("DB_PREFIX")."community c on c.id = h.community_id", 'LEFT')
            ->field("c.name as comm_name, count(h.id) as num")
            ->where($where)->group("comm_name")->select();

        $community = M("community")->field("id,name")->select();
        $houseSt = array();
        foreach($community as $value){
            $houseSt[$value['name']] = array("comm"=>$value['name'], "id"=>$value["id"], "num"=>0);
        }

        foreach ($data as $item) {
            $houseSt[$item['comm_name']]["num"] += $item["num"];
        }

        foreach ($houseSt as $key => $value) {
            $value['name'] = $key;
            $houseInfo[] = $value;
        }
        return $houseInfo;
    }

    /**
     * 分类列表
     */
    public function category(){

        $cid = I("get.cid");
        $category = M("affairscategory")->where(array("id"=>$cid))->find();
        $this->assign("category", $category);

        $list = $this->fn_GetAffairsByCategory($cid, 20);
        $this->assign("list", $list);

        $this->display();
    }

    /**
     * 政务内容详情
     */
    public function show(){
        $sid = I("get.sid");
        M("affairs")->where(array("id"=>$sid))->setInc('rnum');
        $show = M("affairs")->where(array("id"=>$sid))->find();
        $this->assign("show", $show);

        $this->display();
    }

    public function apply(){
        $this->display();
    }

    public function applyNotice(){
        if(I("get.t")==1){
            $url = '/Home/index/applyLzf';
        }else if(I("get.t")==2){
            $url = '/Home/index/applyGzf';
        }else{
            $url = '/Home/index/applyZlbt';
        }
        $this->assign("type", I("get.t"));
        $this->assign('url', $url);
        $this->display();
    }

    public function applyLzf(){
        if(IS_POST){
            $trans = M();
            $trans->startTrans();   // 开启事务
            try{
                //获取廉租房申请的基本信息
                $lzf = $this->fn_GetLzfApply();
                $family = $this->fn_GetLzfApplyFamily();
                $area = $this->fn_GetTownById(I("post.hujidi1"));
                if(!$area){
                    $this->redirect("/Home/index/applyFailed?err_msg=乡镇名称填写有误");
                }

                //申请条件验证
                $this->fn_ApplySubmitCheck($lzf, $family);

                $lzf["hujidi"] = $area["name"] . $lzf["hujidi"];
                $lzf["no"] = $this->fn_GenerateLzfNo();
                $aid = M("lzf")->add($lzf);
                if(!$aid){
                    $this->error(M("lzf")->getLastSql());

                    $this->redirect("/Home/index/applyFailed?err_msg=系统异常，数据写入失败");
                }

                //获取共同申请人信息，最多5个
                for($i=0; $i<count($family); $i++){
                    $family[$i]['lzf_no'] = $lzf["no"];
                    $fid = M("lzf_family")->add($family[$i]);
                    if(!$fid){
                        $this->redirect("/Home/index/applyFailed?err_msg=系统异常，数据写入失败");
                    }
                }

                //获取相关证件信息
                $doc = $this->fn_GetLzfApplyDoc();
                for($i=0; $i<count($doc); $i++){
                    $doc[$i]['lzf_no'] = $lzf["no"];
                    $did = M("lzf_doc")->add($doc[$i]);
                    if(!$did){
                        $this->error("CODE:1002 系统异常，数据写入失败");
                    }
                }

                //获取相关电子证件
                $zj = $this->fn_GetLzfApplyZj();
                $zj["lzf_no"] = $lzf["no"];
                $zid = M("lzf_attach")->add($zj);
                if(!$zid){
                    $this->redirect("/Home/index/applyFailed?err_msg=系统异常，附件数据写入失败");
                }
                $trans->commit();   // 提交事务
                $this->redirect("/Home/index/applySuccess?no=".$lzf["no"]);
            }catch (Exception $e){
                $trans->rollback();   // 开启事务
                $this->error($e->getMessage());
            }
        }

        $applyState = M("apply_state")->where(array("token"=>"default","type"=>"廉租房"))->find();
        if(!$applyState){
            $this->redirect("/Home/index/applyFailed?err_msg=系统尚未开启廉租房申请");
        }
        if($applyState['name']=="关闭申请"){
            $this->redirect("/Home/index/applyFailed?err_msg=".$applyState['reason']);
        }

        $this->assign("community", $this->fn_GetCommunityInfo());
        $this->assign("relation", $this->fn_GetRelation());
        $this->assign("marriage", $this->fn_GetMarriage());
        $this->assign("family_attr", $this->fn_GetFamilyAttr());
        $this->assign("family_huji", $this->fn_GetFamilyHuji());
        $this->assign("area", $this->fn_GetAreaList());
        $this->assign("town", $this->fn_GetTownList());
        $this->display();
    }

    public function fn_GetTownList(){
        $town = M("town")->order("id asc")->select();
        foreach($town as $key => $value){
            $town[$key]['name'] = str_replace("乡", "", $town[$key]['name']);
            $town[$key]['name'] = str_replace("镇", "", $town[$key]['name']);
        }
        return $town;
    }

    public function applyGzf(){
        if(IS_POST){
            $trans = M();
            $trans->startTrans();   // 开启事务
            try{
                //获取廉租房申请的基本信息
                $gzf = $this->fn_GetGzfApply();
                $family = $this->fn_GetGzfApplyFamily();
                $this->fn_ApplySubmitCheck($gzf, $family); //申请条件验证

                $gzf["no"] = $this->fn_GenerateGzfNo();
                $aid = M("gzf")->add($gzf);
                if(!$aid){
                    $this->redirect("/Home/index/applyFailed?err_msg=系统异常，数据写入失败");
                }

                //获取共同申请人信息，最多4个
                for($i=0; $i<count($family); $i++){
                    $family[$i]['gzf_no'] = $gzf["no"];
                    $fid = M("gzf_family")->add($family[$i]);
                    if(!$fid){
                        $this->redirect("/Home/index/applyFailed?err_msg=系统异常，数据写入失败");
                    }
                }

                //获取相关电子证件
                $zj = $this->fn_GetGzfApplyZj();
                $zj["gzf_no"] = $gzf["no"];
                $zid = M("gzf_attach")->add($zj);
                if(!$zid){
                    $this->redirect("/Home/index/applyFailed?err_msg=系统异常，附件数据写入失败");
                }
                $trans->commit();   // 提交事务
                $this->redirect("/Home/index/applySuccess?no=".$gzf["no"]);
            }catch (Exception $e){
                $trans->rollback();   // 开启事务
                $this->error($e->getMessage());
            }
        }

        $applyState = M("apply_state")->where(array("token"=>"default","type"=>"公租房"))->find();
        if(!$applyState){
            $this->redirect("/Home/index/applyFailed?err_msg=系统尚未开启廉租房申请");
        }
        if($applyState['name']=="关闭申请"){
            $this->redirect("/Home/index/applyFailed?err_msg=".$applyState['reason']);
        }

        $this->assign("community", $this->fn_GetCommunityInfo());
        $this->assign("gender", $this->fn_GetGender());
        $this->assign("relation", $this->fn_GetRelation());
        $this->assign("marriage", $this->fn_GetMarriage());
        $this->assign("work_state", $this->fn_GetWorkState());
        $this->assign("house_state", $this->fn_GetHouseState());
        $this->assign("applier_type", $this->fn_GetApplierType());
        $this->assign("area", $this->fn_GetAreaList());
        $this->display();
    }

    public function applyZlbt(){
        if(IS_POST){
            $trans = M();
            $trans->startTrans();   // 开启事务
            try{
                //获取租赁补贴申请的基本信息
                $zlbt = $this->fn_GetZlbtApply();
                $family = $this->fn_GetLzfApplyFamily();
                $area = $this->fn_GetTownById(I("post.hujidi1"));
                if(!$area){
                    $this->redirect("/Home/index/applyFailed?err_msg=乡镇名称填写有误");
                }

                //申请条件验证
                $this->fn_ApplySubmitCheck($zlbt, $family);
                $zlbt["hujidi"] = $area["name"] . $zlbt["hujidi"];
                $zlbt["no"] = $this->fn_GenerateZlbtNo();
                $aid = M("zlbt")->add($zlbt);
                if(!$aid){
                    $this->redirect("/Home/index/applyFailed?err_msg=系统异常，数据写入失败");
                }

                //获取共同申请人信息，最多5个
                for($i=0; $i<count($family); $i++){
                    $family[$i]['zlbt_no'] = $zlbt["no"];
                    $fid = M("zlbt_family")->add($family[$i]);
                    if(!$fid){
                        $this->redirect("/Home/index/applyFailed?err_msg=系统异常，数据写入失败");
                    }
                }

                //获取相关证件信息
                $doc = $this->fn_GetLzfApplyDoc();
                for($i=0; $i<count($doc); $i++){
                    $doc[$i]['zlbt_no'] = $zlbt["no"];
                    $did = M("zlbt_doc")->add($doc[$i]);
                    if(!$did){
                        $this->error("CODE:1002 系统异常，数据写入失败");
                    }
                }

                //获取相关电子证件
                $zj = $this->fn_GetLzfApplyZj();
                $zj["zlbt_no"] = $zlbt["no"];
                $zid = M("zlbt_attach")->add($zj);
                if(!$zid){
                    $this->redirect("/Home/index/applyFailed?err_msg=系统异常，附件数据写入失败");
                }
                $trans->commit();   // 提交事务
                $this->redirect("/Home/index/applySuccess?no=".$zlbt["no"]);
            }catch (Exception $e){
                $trans->rollback();   // 开启事务
                $this->error($e->getMessage());
            }
        }

        $period = $this->fn_GetAvailableRequest();
        if(!$period){
            $this->redirect("/Home/index/applyFailed?err_msg=本季度尚未开放申请，请及时关注官网新闻");
        }

        $this->assign("period", $period);
        $this->assign("relation", $this->fn_GetRelation());
        $this->assign("marriage", $this->fn_GetMarriage());
        $this->assign("family_attr", $this->fn_GetFamilyAttr());
        $this->assign("family_huji", $this->fn_GetFamilyHuji());
        $this->assign("area", $this->fn_GetAreaList());
        $this->assign("town", $this->fn_GetTownList());
        $this->display();
    }

    /**
     * 房屋自动补全搜索算法
     */
    public function ajax_SearchHouseByAddr(){
        $h = array();
        $where = array("state"=>"闲置中","addr"=>array("like", "%".I("get.house_addr")."%"));
        $house = M("house")->where($where)->field("id,addr")->limit(10)->select();
        foreach ($house as $v){
            array_push($h, array("value"=>$v["addr"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.house_addr"), 'suggestions' => $h));
    }

    public function applyFailed(){
        $this->assign("err_msg", I("get.err_msg"));
        $this->display();
    }

    public function applySuccess(){
        $this->assign("no", I("get.no"));
        $this->display();
    }

    public function leaveMsg(){
        $category = $this->fn_GetCategoryList();
        $this->assign("category", $category);
        $this->display();
    }

    public function ajax_UploadImg(){

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     2048000;// 设置附件上传大小，1M以内
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Public/UPLOADS/'; // 设置附件上传根目录

        // 上传文件
        $info   =   $upload->uploadOne($_FILES["file"]);
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            $path = '/Public/UPLOADS/'.$info['savepath'].$info['savename'];
            $this->success($path);
        }

    }

    public function ajax_QueryProgress(){

        $name = I("post.name");
        $idno = I("post.idno");
        if(strlen($idno)!=18){
            $this->error("无效的身份证号码");
        }

        $no = I("post.no");
        $reason = null;
        if(I("post.t")=="ns"){
            $code = $this->fn_GetNsStateCode($name, $idno, $no, $reason);
        }else{
            $code = $this->fn_GetSqStateCode($name, $idno, $no, $reason);
        }
        $reponse = $this->fn_RenderEchoTmpl($code, $reason);
        $this->success($reponse);
    }

    protected function fn_RenderEchoTmpl($code, $reason=null){
        $echo = M("tmplecho t")
            ->field("t.*, c.name as company_name, c.phone")
            ->join(C("DB_PREFIX")."company c on c.id=t.company_id", "LEFT")
            ->where(array('t.state'=>$code))->find();
        $echo = strtr($echo['content'], [
            "{{company}}" => $echo['company_name'],
            "{{phone}}" => $echo["phone"],
            "{{reason}}" => $reason
        ]);
        return $echo;
    }

    private function fn_GetModelByPrefix($prefix){
        if($prefix=="L"){
            return "lzf";
        }else if($prefix=="G"){
            return "gzf";
        }else if($prefix=="Z"){
            return "zlbt";
        }
        return null;
    }

    //查询年审进度代码
    private function fn_GetNsStateCode($name, $idno, $houseAddr, &$reason){
        $nsBatch = M("nianshen_batch")->where(array("state"=>"已启动"))->find();
        if(!$nsBatch){  //年审未启动
            return "unstart";
        }

        $where = array("addr"=>$houseAddr);
        $house = M("house")->field("id,name")->where($where)->find();
        if(!$house){
            $this->error("没有找到房源信息");
        }

        $where = array("name"=>$name, "idno"=>$idno, "house_no"=>$house['name'], "year"=>$nsBatch['year']);
        $nianshen = M("nianshen")->field("no,state")->where($where)->find();
        if(!$nianshen){
            $this->error("没有查询到相关年审信息");
        }

        if($nianshen['state']=='审核通过'){
            return "pass";
        }else if($nianshen['state']=='审核失败'){
            $reason = $nianshen['opinion'];
            return "unpass";
        }

        //联合审批中
        $where = array("no"=>$nianshen['no'], "spzt"=>"未审批");
        $lhsp = M("lhsp")->field("spdw")->where($where)->order("id asc")->select();
        foreach($lhsp as $item){
            return self::$companyStatusMapping[ $item['spdw'] ];
        }
        return 'started';
    }

    //查询申请进度代码
    private function fn_GetSqStateCode($name, $idno, $no, &$reason){

        if(strlen($no)<7){
            $this->error("无效的申请编号");
        }
        $prefix = substr($no, 0, 1);
        if(!in_array($prefix, array("L", "G", "Z"))){
            $this->error("无效的申请编号");
        }
        $model = $this->fn_GetModelByPrefix($prefix);
        $where = array("no"=>$no, "name"=>$name, "idno"=>$idno);
        $apply = M($model)->where($where)->find();
        if(!$apply){
            $this->error("没有查询到相关申请信息");
        }

        if($apply['state']=='failed'){
            $reason = $apply['reason'];
        }

        $state = array(
            "submit", "pass1", "pass2", "pass3", "failed", "done", "refuse"
        );
        if(in_array($apply['state'], $state)){
            return $apply['state'];
        }

        if($model=='zlbt' && $apply['state']=='pass4'){  //待分配房源，待发放补贴
            return "unpaid";
        }

        if($apply['state']=='pass4'){
            return "pass4";
        }

        //联合审批中
        $where = array("no"=>$apply['no'], "spzt"=>"未审批");
        $lhsp = M("lhsp")->field("spdw")->where($where)->order("id asc")->select();
        //..............$this->error(M("lhsp")->getLastSql());
        foreach($lhsp as $item){
            return self::$companyStatusMapping[ $item['spdw'] ];
        }
        return 'accept';
    }

    public function ajax_LeaveMsg()
    {
        $data = array(
            "name" => I("post.name"),
            "phone" => I("post.phone"),
            "addr" => I("post.addr"),
            "email" => I("post.email"),
            "title" => I("post.title"),
            "category" => I("post.category"),
            "content" => I("post.content"),
            "state" => 0,
            "ip" => $_SERVER['REMOTE_ADDR'],
            "ctime" => time(),
        );
        $dataId = M("message")->add($data);
        if($dataId){
            $this->success("留言成功");
        }else{
            $this->error("系统错误，操作失败");
        }
    }

    protected function fn_GetFamilyHuji(){
        return self::$hujiqk;
    }

    protected function fn_GetMarriage(){
        return self::$marriage;
    }

    protected function fn_GetGender(){
        return self::$gender;
    }

    protected function fn_GetRelation(){
        return self::$relation;
    }

    protected function fn_GetFamilyAttr(){
        return self::$attr;
    }

    protected function fn_IsLzfInfoExist($no, $name, $idno){
        $where = array("no"=>$no, "name"=>$name, "idno"=>$idno);
        $res = M("lzf")->where($where)->find();
        return $res?$res:false;
    }

    protected function fn_IsGzfInfoExist($no, $name, $idno){
        $where = array("no"=>$no, "name"=>$name, "idno"=>$idno);
        $res = M("gzf")->where($where)->find();
        return $res?$res:false;
    }

    public function fn_ApplySubmitCheck($apply, $family){
        //获取申请人及共同申请人的身份证信息
        $idnos = array($apply['idno']);
        foreach ($family as $item) {
            if($item['idno']){
                $idnos[] = $item["idno"];
            }
        }

        //第一步：是否有重复申请
        $where = array(
            "state"=>array("in", array("submit", "accept", "pass1", "pass2", "pass3", "pass4", "done")),
            "idno" => array("in", $idnos)

        );
        $res = M("lzf")->where($where)->find();
        if($res){
            $msg = "申请人或共同申请人已经申请了廉租房，不能重复申请";
            $this->redirect("/Home/index/applyFailed?err_msg=".$msg);
        }

        //第二步：是否位有申请过公租房
        $where = array(
            "state"=>array("in",
                array("submit", "accept", "pass1", "pass2", "pass3", "pass4", "done")
            ),
            "idno" => array("in", $idnos)
        );
        $res = M("gzf")->where($where)->find();
        if($res){
            $this->error(M("gzf")->getLastSql());
            $msg = "申请人或共同申请人已经申请了公租房，不能重复申请";
            $this->redirect("/Home/index/applyFailed?err_msg=".$msg);
        }

        //第三步：是否位有申请过租赁补贴
        $where = array(
            "state"=>array("in",
                array("submit", "accept", "pass1", "pass2", "pass3", "pass4"),
                "idno" => array("in", $idnos)
            )
        );
        $res = M("zlbt")->where($where)->find();
        if($res){
            $msg = "申请人或共同申请人已经申请了租赁补贴，不能重复申请";
            $this->redirect("/Home/index/applyFailed?err_msg=".$msg);
        }

        //第四步：是否位置黑名单中
        $where = array("idno" => array("in", $idnos));
        $res = M("blacklist")->where($where)->find();
        if($res){
            $msg = "申请人或共同申请人申请被拒绝";
            $this->redirect("/Home/index/applyFailed?err_msg=".$msg);
        }
    }

    protected function fn_ResponseStateMapping($apply){
        $state = array(
            "submit", "pass1", "pass2", "pass3", "done", "failed", "refuse"
        );
        if(in_array($apply['state'], $state)){
            return $apply['state'];
        }

        if($apply['state']=='pass4'){  //待分配房源，待发放补贴
            if(substr($apply['no'], 0, 1)=='Z'){
                return "unpaid";
            }else{
                return 'pass4';
            }
        }
        if($apply['state']=='accept'){   //联合审批
            if(array_key_exists("csjzjsp", $apply) and !$apply['csjzjsp']){ //城市救助局（低保办）
                return "city";
            }else if(array_key_exists("clglssp", $apply) and !$apply['clglssp']){ //车管所
                return "car";
            }else if(array_key_exists("gjjglbsp", $apply) and !$apply['gjjglbsp']){ //公积金
                return "fund";
            }else if(array_key_exists("bdcdjjsp", $apply) and !$apply['bdcdjjsp']){ //不动产
                return "house";
            }else if(array_key_exists("gsjsp", $apply) and !$apply['gsjsp']){ //工商局
                return "industry";
            }else if(array_key_exists("sqsp", $apply) and !$apply['sqsp']){ //社区审批
                return "community";
            }else if(array_key_exists("rsjsp", $apply) and !$apply['rsjsp']){  //人社局
                if($apply['work_state']=='机关事业单位'){
                    return "goverment";
                }else{
                    return "enterprise";
                }
            }else{
                return "accept";  //联合审批完成，待提交房产局提交到下一个流程
            }
        }
        return null;
    }

    private function fn_GetAffairsCategory(){
        $where = array("active"=>1);
        return M("affairscategory")->field("id, name")->where($where)->order("seq asc")->select();
    }

    private function fn_GetAffairsByCategory($catId, $num){
        $where = array("category"=>$catId);
        return M("affairs")->field("id,title,ctime")->where($where)->order("seq asc, id desc")->limit($num)->select();
    }

    protected function fn_GetApplierType(){
        //return M("applier_type")->where()->select();
        return self::$applierType;
    }

    protected function fn_GetHouseState(){
        //return M("house_state")->where()->select();
        return self::$houseState;
    }

    protected function fn_GetWorkState(){
        //return M("work_state")->where()->select();
        return self::$workState;
    }

    public function fn_GetAreaList(){
        return M("area")->order("seq asc")->select();
    }

    private function fn_GenerateLzfNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("lzf_no")->add($data);
        return "L".$no;
    }

    private function fn_GenerateZlbtNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("zlbt_no")->add($data);
        return "Z".$no;
    }

    private function fn_GenerateGzfNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("gzf_no")->add($data);
        return "G".$no;
    }

    private function fn_GetTownById($townId){
        //$where = 'name in ("'.$areaName.'镇", "'.$areaName.'乡")';
        $where = array("id" => $townId);
        return M("town")->field("id, name")->where($where)->find();
    }

    protected function fn_GetLzfApply(){
        return array(
            "name" => I("post.name"),
            "marriage" => I("post.marriage"),
            "idno" => I("post.idno"),
            "gender" => I("post.gender"),
            "dibao" => I("post.dibao"),
            "dibaohm" => I("post.dibaohm"),
            "dibaork" => I("post.dibaork"),
            "resident_num" => I("post.resident_num"),
            "area_id" => I("post.area_id"),
            "community_id" => I("post.community_id"),
            "addr" => I("post.addr"),
            "attr" => implode(',', I("post.attr")),
            "phone" => I("post.phone"),
            "hujidi" => I("post.hujidi2")."村".I("post.hujidi3")."组",
            "hujidi1" => I("post.hujidi1"),
            "hujidi2" => I("post.hujidi2"),
            "hujidi3" => I("post.hujidi3"),
            "hujiqk" => implode(',',I("post.hujiqk")),
            "gxincome" => I("post.gxincome"),
            "ccincome" => I("post.ccincome"),
            "income" => I("post.income"),
            "estate" => I("post.estate"),
            "stime" => time(),
            "ip" => get_client_ip(),
        );
    }

    protected function fn_GetZlbtApply(){
        return array(
            "name" => I("post.name"),
            "period" => I("post.period_code"),
            "bankno" => I("post.bankno"),
            "marriage" => I("post.marriage"),
            "idno" => I("post.idno"),
            "gender" => I("post.gender"),
            "dibao" => I("post.dibao"),
            "dibaohm" => I("post.dibaohm"),
            "dibaork" => I("post.dibaork"),
            "area_id" => I("post.area_id"),
            "addr" => I("post.addr"),
            "attr" => implode(',', I("post.attr")),
            "phone" => I("post.phone"),
            "hujidi" => I("post.hujidi2")."村".I("post.hujidi3")."组",
            "hujidi1" => I("post.hujidi1"),
            "hujidi2" => I("post.hujidi2"),
            "hujidi3" => I("post.hujidi3"),
            "hujiqk" => implode(',',I("post.hujiqk")),
            "gxincome" => I("post.gxincome"),
            "ccincome" => I("post.ccincome"),
            "income" => I("post.income"),
            "estate" => I("post.estate"),
            "stime" => time(),
            "ip" => get_client_ip(),
            "familyrk" => I("post.familyrk")
        );
    }

    protected function fn_GetGzfApply(){
        return array(
            "name" => I("post.name"),
            "idno" => I("post.idno"),
            "marriage" => I("post.marriage"),
            "gender" => I("post.gender"),
            "resident_num" => I("post.resident_num"),
            "coapply_num" => I("post.coapply_num"),
            "phone" => I("post.phone"),
            "company" => I("post.company"),
            "work_date" => I("post.work_date"),
            "area_id" => I("post.area_id"),
            "community_id" => I("post.community_id"),
            "work_state" => I("post.work_state"),
            "house_state" => I("post.house_state"),
            "pay_shebao" => I("post.pay_shebao"),
            "pay_date1" => I("post.pay_date1"),
            "pay_date2" => I("post.pay_date2"),
            "applier_type" => I("post.applier_type"),
            "gxincome" => I("post.gxincome"),
            "ccincome" => I("post.ccincome"),
            "income" => I("post.income"),
            "gxincome2" => I("post.gxincome2"),
            "ccincome2" => I("post.ccincome2"),
            "income2" => I("post.income2"),
            "stime" => time(),
            "ip" => get_client_ip(),
        );
    }

    protected function fn_GetLzfApplyFamily(){
        $family = array();
        for($i=1; $i<=5; $i++){
            if(I("post.sq-name$i")){
                $member = array(
                    "name" => I("post.sq-name$i"),
                    "age" => I("post.sq-age$i"),
                    "phone" => I("post.sq-phone$i"),
                    "gender" => $this->fn_GetGenderByIdno(I("post.sq-idno$i")),
                    "relation" => I("post.sq-relation$i"),
                    "rrelation" => I("post.sq-rrelation$i"),
                    "idno" => I("post.sq-idno$i"),
                    "bxhk" => I("post.sq-bxhk$i"),
                    "income" => I("post.sq-income$i"),
                    "sfzImg" => I("post.sq-sfzImg$i"),
                    "hkbImg" => I("post.sq-hkbImg$i"),
                    "tssq" => I("post.sq-tssq$i")
                );
                array_push($family, $member);
            }
        }
        return $family;
    }

    protected function fn_GetGzfApplyFamily(){
        $family = array();
        for($i=1; $i<=5; $i++){
            if(I("post.sq-name$i")){
                $member = array(
                    "name" => I("post.sq-name$i"),
                    "relation" => I("post.sq-relation$i"),
                    "age" => $this->fn_GetAgeByIdno(I("post.sq-idno$i")),
                    "gender" => $this->fn_GetGenderByIdno(I("post.sq-idno$i")),
                    "phone" => I("post.sq-phone$i"),
                    "idno" => I("post.sq-idno$i"),
                    "company" => I("post.sq-company$i"),
                    "marriage" => I("post.sq-marriage$i"),
                    //"huji" => I("post.sq-huji$i"),
                    "income" => I("post.sq-income$i"),
                    "sfzImg" => I("post.sq-sfzImg$i"),
                    "hkbImg" => I("post.sq-hkbImg$i"),
                );
                array_push($family, $member);
            }
        }
        return $family;
    }

    public function fn_GetAgeByIdno($idno){
        $tag = substr($idno, 6, 4);
        return intval(date("Y")-$tag);
    }

    public function fn_GetGenderByIdno($idno){
        $tag = substr($idno, 16, 1);
        if($tag%2=='1'){
            return "男";
        }else if($tag%2==0){
            return "女";
        }
        return null;
    }

    protected function fn_GetLzfApplyDoc(){
        $doc = array();
        $arr = array(
            array("pre"=>"db-", "name"=>"低保证"),
            array("pre"=>"cj-", "name"=>"残疾人证"),
            array("pre"=>"jl-", "name"=>"军烈属证"),
            array("pre"=>"fw-", "name"=>"房屋所有权证"),
        );
        for($i=0; $i<count($arr); $i++){
            $name = $arr[$i]["pre"]."idname";
            if(I("post.".$name)){
                $item = array(
                    "name" => $arr[$i]["name"],
                    "idname" => I("post.".$arr[$i]["pre"]."idname"),
                    "fzdate" => I("post.".$arr[$i]["pre"]."fzdate"),
                    "fzdw" => I("post.".$arr[$i]["pre"]."fzdw"),
                    "no" => I("post.".$arr[$i]["pre"]."no"),
                    "zjImg" => I("post.".$arr[$i]["pre"]."zjImg"),
                    "yxdate" => I("post.".$arr[$i]["pre"]."yxdate"),
                    "remarks" => I("post.".$arr[$i]["pre"]."remarks")
                );
                array_push($doc, $item);
            }
        }
        return $doc;
    }

    protected function fn_GetLzfApplyZj(){
        return array(
            "sfzzmImg" => I("post.sfzzmImg"), //申请人身份证正面
            "sfzbmImg" => I("post.sfzbmImg"), //申请人身份证背面
            "hkbImg" => I("post.hkbImg"), //申请人户口簿
            "jhzImg" => I("post.jhzImg"), //申请人结婚证
            "lhzImg" => I("post.lhzImg"), //申请人离婚证
            "zlImg" => I("post.zlImg") //仅对租赁补贴申请有效
        );
    }

    protected function fn_GetGzfApplyZj(){
        return array(
            "sfzzmImg" => I("post.sfzzmImg"), //申请人身份证正面
            "sfzbmImg" => I("post.sfzbmImg"), //申请人身份证背面
            "hkbImg" => I("post.hkbImg"), //申请人户口簿
            "jhzImg" => I("post.jhzImg"), //申请人结婚证
            "lhzImg" => I("post.lhzImg"), //申请人离婚证
            "pyzmImg" => I("post.pyzmImg"), //聘用证明
            "sbImg" => I("post.sbImg"), //社保证明
            "dbzImg" => I("post.dbzImg"), //低保证明
            "txzImg" => I("post.txzImg"), //退休证
            "yhlsImg" => I("post.yhlsImg"), //银行流水
            "fpzImg" => I("post.fpzImg"), //扶贫证
            "tsrcImg" => I("post.tsrcImg"), //特殊人才证明
        );
    }

    protected function fn_GetAvailableRequest(){
        $where = array("state"=>"已启动", "end_date"=>array("gt", time()));
        return M("zlbt_period")->field("name,code")->where($where)->find();
    }

    /**
     * 获取政务分类信息2 key => value
     * @return mixed
     */
    public function fn_GetCategoryDict(){
        $result = array();
        $category = M("messagecategory")->where(array("active"=>1))->order("seq asc")->select();
        for($i=0; $i<count($category); $i++){
            $result[$category[$i]["id"]] = $category[$i]["name"];
        }
        return $result;
    }

    public function fn_GeneratePages($page, $where, $num=5){

        $result = array(
            "firstPage" => 1,
            "nextPage" => 1,
            "prevPage" => 1,
            "lastPage" => 1,
            "curPage" => $page,
            "totalPage" => 1,
            "pageList" => array()
        );
        $total = M("message")->where($where)->count();
        $totalPage = ceil($total/$num);

        $result["totalPage"] = $totalPage;
        $result["lastPage"] = $totalPage;
        $result["nextPage"] = min($totalPage, $page+1);
        $result["prevPage"] = max(1, $page-1);

        for($i=1; $i<=$totalPage; $i++){
            $result["pageList"][] = $i;
        }

        return $result;
    }

    /**
     * 获取政务分类信息  array
     * @return mixed
     */
    public function fn_GetCategoryList(){
        return M("messagecategory")->where(array("active"=>1))->order("seq asc, id desc")->select();
    }

}